//pinia状态管理
import { defineStore } from 'pinia'
import { GetSongUrl, GetSongInfo, GetSongLyric } from '@/api/api.ts'
import { parseLyrics } from '@/utils/formatSongLyric'
import type { SongUrl } from '@/models/songurl'
import type { Songinfo, Lyric } from '@/models/songinfo'
export const usePlaySongStore = defineStore({
  id: 'playsong',
  state: () => ({
    historyplaysongids: [] as number[],//历史播放
    songurl: {} as SongUrl,//当前播放歌曲的url
    songinfo: {} as Songinfo,//歌曲信息包含图片、名字等
    songlyric: {} as Lyric[],//当前播放歌曲的歌词
    IsShowLyric: false,//是否显示歌词
    index: 0,//历史播放的索引
    audio: new Audio(),
    audioVolume: 1, // 音频声音，范围 0-1
    playStatus: false, // 音频播放状态：true 播放，false 暂停
    playProgress: 0, // 音频播放进度
    audioDuration: 0, // 音频总时长
    audioCurrent: 0, // 音频当前播放时间
    timeInterval: '' as any,
  }),
  getters: {

  },
  actions: {
    //获取播放音乐的数据 
    async playsong(id: number) {
      const url = await GetSongUrl(id)
      this.songurl = url.data.data[0]
      const info = await GetSongInfo(id)
      this.songinfo = info.data.songs[0]
      const lyric = await GetSongLyric(id)
      this.songlyric = parseLyrics(lyric.data.lrc.lyric)
    },
    //历史播放中是否有音乐
    isHave(id: number) {
      //判断历史播放是否有该id  -1:没有则把id放在历史播放中   
      if (this.historyplaysongids.indexOf(id) == -1) {
        this.historyplaysongids.push(id)
        this.playsong(id)
        this.index = this.historyplaysongids.indexOf(id)

      } else {  //不等于-1:有则返回索引
        this.playsong(id)
        this.index = this.historyplaysongids.indexOf(id)
      }
    },
    //上一首
    beforeSong() {
      let i = this.index
      i = i - 1
      if (i < 0) {
        i = this.historyplaysongids.length - 1
        this.playsong(this.historyplaysongids[i])
        this.index = i
      } else {
        this.playsong(this.historyplaysongids[i])
        this.index = i
      }

    },
    //下一首
    nextoSong() {
      let i = this.index
      i = i + 1
      if (i > this.historyplaysongids.length - 1) {
        i = 0
        this.playsong(this.historyplaysongids[i])
        this.index = i
      } else {
        this.playsong(this.historyplaysongids[i])
        this.index = i
      }
    },
  },
});
